
//"#regin"
//=================================================================================================================
var Transform = function (mc) {
    //初始速度
    let start_speed
    //设置位置//向量或者2个点
    mc.setPosition = function (v, p2) {
        if (p2 == undefined) {
            this.x = v?.x;
            this.y = v?.y;
        } else {
            this.x = v;
            this.y = p2;
        }
    },
        //向着V方向移动
        mc.move = function (v) {
            this.x += v.x;
            this.y += v.y;
        },
        ////向着V移动，移动到V的位置后停止
        mc.moveTo = function (v, speed = 1, coef) {
            if (Vector.distance(this, v) <= 3) {
                this.x = v.x;
                this.y = v.y;
                return true
            }
            if (coef != undefined) {
                coef = Clamp01(coef)
                //onlyOneFn(new Vector(this.x, this.y))
                // this.x = start_speed.x + (v.x - start_speed.x) * coef;
                // this.y = start_speed.y + (v.y - start_speed.y) * coef;
                this.x = this.x + (v.x - this.x) * coef;
                this.y = this.y + (v.y - this.y) * coef;
                // console.log(this.x + "=" + coef)
                // this.y += v.y * start_speed;
            } else {
                //方向
                v = new Vector(v?.x - this.x, v?.y - this.y)
                //单位1
                v = v.normal()
                this.x += v.x * speed;
                this.y += v.y * speed;
            }
            // console.log(this.x)
        }
    //获取中心点的位置
    ////向着V移动，移动到V的位置后停止
    mc.getCenterPot = function () {
        return new Vector(this.x - this.regX, this.y - this.regY)
    }
    //  console.log(this.c)
    function Clamp01(value) {
        if (value < 0) {
            return 0;
        }
        if (value > 1) {
            return 1;
        }
        return value;
    }
}(createjs.MovieClip.prototype)
//====================================================================================================================
var tools = function () {
    var TickS = []
    createjs.addTick = (f) => {
        TickS.push(f)
    }
    createjs.Ticker.addEventListener("tick", handleTick);
    function handleTick(event) {
        // Actions carried out each tick (aka frame)
        if (!event.paused) {
            // 无限循环的函数
            TickS.forEach((f) => {
                f()
            })
        }
    }

    //***********************
    //只执行一次方法
    window.G_onlyOneFn = once(function (f) {
        f()
        // console.log('once')
    })
    //只执行一次方法
    function once(fn) {
        let caller = true;
        // console.log(caller)
        return function () {
            if (caller) {
                caller = false
                // console.log(caller)
                fn.apply(this, arguments)
            }
        }
    }

    //声音播放结束回调
    window.G_PlayAudio = (name, callBack, audNo, delayTime = 0.5) => {
        let url = "sounds/" + name + ".mp3"
        if (aud == undefined) {
            aud = $("#aud" + audNo)[0]
        }
        aud.src = url
        aud.load()
        aud.play()
        aud.onended = function () {
            //  aud.src = ""
            setTimeout(function () {
                callBack(aud)
            }, delayTime * 1000)

        }
        return aud
    }


    //双击或者多击事件
    window.G_doubleClick = (handle, awt = 500, n = 2) => {
        let count = 0;
        let timer = null;
        return function () {
            if (!timer) {
                timer = setTimeout(function () {
                    count = 0;
                    timer = null;
                }, awt);
            }
            count++;
            if (count === n) {
                handle();
                count = 0;
                clearTimeout(timer);
                timer = null;
            }
        }
    }
    //延迟执行函数
    // function G_Delay(func, time) {
    //     setTimeout(function () {
    //         func()
    //     }, time * 1000)
    // }
    //1拖动对象2.是否画线
    window.G_drag = function (...agr) {
        agr.forEach(function (e) {
            //检测显示对象是否与鼠标点碰撞
            e.on("mousedown", function () {
                e.drag_bool = true
                if (e.mousedown != undefined) {
                    e.mousedown(e)
                }
                //深度设置
                G_setIndex(e)
            })
            //鼠标抬起
            e.on("pressup", function () {
                e.drag_bool = false
                if (e.mouseup != undefined) {
                    // console.log(this.obj.stagemouseup)
                    e.mouseup()
                }
            })
            //鼠标移动
            e.on("pressmove", function (a) {
                if (!e.drag_bool) { return }
                var pt = e.parent?.globalToLocal(a.stageX, a.stageY)
                e.x = pt.x
                e.y = pt.y
                if (e.mousemove != undefined) {
                    e.mousemove(e)
                }
            })
        });
    }

    //1拖动对象，限制x轴或者y轴
    window.G_drag2 = function (obj, xy, section) {
        //检测显示对象是否与鼠标点碰撞
        obj.section = section//区间，运动的范围[min,max]
        obj.xy = xy//是x轴运动还是y轴
        obj.on("mousedown", function () {
            obj.drag_bool = true
            if (obj.mousedown != undefined) {
                obj.mousedown()
            }
            //深度设置
            G_setIndex(obj)
        })
        //鼠标抬起
        obj.on("pressup", function () {
            obj.drag_bool = false
            if (obj.mouseup != undefined) {
                obj.mouseup()
            }
        })
        //鼠标移动
        obj.on("pressmove", function (a) {
            if (!obj.drag_bool) { return }
            let pt = obj.parent.globalToLocal(a.stageX, a.stageY)
            if (obj.xy == "x" && obj.section[0] <= pt.x && obj.section[1] >= pt.x) {
                obj.x = pt.x
            } if (obj.xy == "y" && obj.section[0] <= pt.y && obj.section[1] >= pt.y) {
                obj.y = pt.y
            } else if (obj.xy == undefined) {
                obj.x = pt.x
                obj.y = pt.y
            }
            if (obj.mousemove != undefined) {
                obj.mousemove()
            }
        })
    }

    //深度设置，1,个参数的时候，设置最高，2个参数的时候交换
    window.G_setIndex = (obj1, obj2) => {
        let op1 = obj1.parent
        if (obj2 == undefined) {
            op1.swapChildrenAt(op1.getChildIndex(obj1), op1.numChildren - 1)
        } else {
            if (obj1.parent.id != obj2.parent.id) {
                throw console.error("不是同一个父级，不能交换深度");
            }
            op1.swapChildren(obj1, obj2)
        }
    }

    ///;;........................................................
    //与多个点检测//如果发生了碰撞返回碰撞的对象，没有碰撞就返回false
    window.G_hit2 = function (target, ptArr) {
        for (let i = 0; i < ptArr.length; i++) {
            if (G_hit(target, ptArr[i]) != false) {
                //  console.log("发生了碰撞=" + ptArr[i].name)
                //发生了碰撞
                return ptArr[i]
            }
        }
        return false
    }
    //碰撞检查//如果发生了碰撞返回碰撞的对象，没有碰撞就返回false
    window.G_hit = function (target, pt) {
        // console.log(pt.parent)
        if (target == undefined || pt == undefined || pt.parent == null) {
            return
        }
        pt = pt.parent.localToLocal(pt.x, pt.y, target)
        //pt = target.globalToLocal(pt.x, pt.y)
        if (target.hitTest(pt.x, pt.y) && target != undefined) {
            return true
        } else {
            return false
        }
    }



    ///;;........................................................
    //重力函数
    var G = 0.5
    //var G_startSpeed = 0
    const G_objs = new Map()
    //console.log(G_objs.values())
    window.G_add_gravity = function (obj, callBack) {
        obj.G_startSpeed = 0
        G_objs.set(obj.id, obj)
        obj.gravity_callback_f = callBack
    }
    window.G_remove_gravity = function (obj) {
        if (G_objs.has(obj.id)) {
            G_objs.delete(obj.id)
        }
    }
    createjs.addTick(() => {
        G_objs.forEach(function (v) {
            v.G_startSpeed += G
            v.y += v.G_startSpeed
            if (v.gravity_callback_f != undefined) {
                v.gravity_callback_f()
            }
            // console.log(v.G_startSpeed)
        })
    })


    //--------------------------------------------------------------------------------------
    //适量转位图
    window.G_SSB = function (obj, f, bool) {
        let pt = new createjs.Point(obj.x, obj.y)
        let parent = obj.parent
        if (!bool) {
            parent.removeChild(obj)
        }
        //var huo = new lib.huo(); //矢量影片剪辑
        var spritesheetBuilder = new createjs.SpriteSheetBuilder();
        spritesheetBuilder.addMovieClip(obj);
        spritesheetBuilder.addEventListener("progress", function (event) {
            //console.log(event, "<<<<<<<<<<<<<<<<") //渲染进度
            //alert(6)
        })
        spritesheetBuilder.addEventListener("complete", function (event) {
            //console.log("complete", spritesheetBuilder.spriteSheet)
            spritesheetBuilder.stopAsync();
            renderCompleteHandler(spritesheetBuilder.spriteSheet)
        })
        spritesheetBuilder.buildAsync();
        function renderCompleteHandler(sheet) {
            //spritesheet = sheet;
            let sprite = new createjs.Sprite(sheet);
            sprite.x = pt.x
            sprite.y = pt.y
            parent.addChild(sprite); //在这里矢量已经变成位图
            // console.log(sprite)
            f(sprite)
            //sprite.play()
        }
    }


    //适量转位图
    window.G_SSB2 = function (obj, parent, x, y, f) {
        //var huo = new lib.huo(); //矢量影片剪辑
        var spritesheetBuilder = new createjs.SpriteSheetBuilder();
        spritesheetBuilder.addMovieClip(obj);
        spritesheetBuilder.addEventListener("progress", function (event) {
            //console.log(event, "<<<<<<<<<<<<<<<<") //渲染进度
            //alert(6)
        })
        spritesheetBuilder.addEventListener("complete", function (event) {
            //console.log("complete", spritesheetBuilder.spriteSheet)
            spritesheetBuilder.stopAsync();
            renderCompleteHandler(spritesheetBuilder.spriteSheet)
        })
        spritesheetBuilder.buildAsync();
        function renderCompleteHandler(sheet) {
            //spritesheet = sheet;
            var sprite = new createjs.Sprite(sheet);
            parent.addChild(sprite); //在这里矢量已经变成位图
            sprite.x = x
            sprite.y = y
            f(sprite)
            //sprite.play()
        }
    }

    //适量转位图
    window.G_SSB2 = function (obj, f) {
        //var huo = new lib.huo(); //矢量影片剪辑
        var spritesheetBuilder = new createjs.SpriteSheetBuilder();
        spritesheetBuilder.addMovieClip(obj);
        //spritesheetBuilder.addMovieClip(obj2);
        //spritesheetBuilder.addFrame(obj2)
        spritesheetBuilder.addEventListener("progress", function (event) {
            //console.log(event, "<<<<<<<<<<<<<<<<") //渲染进度
            //alert(6)
        })
        spritesheetBuilder.addEventListener("complete", function (event) {
            //console.log("complete", spritesheetBuilder.spriteSheet)
            spritesheetBuilder.stopAsync();
            renderCompleteHandler(spritesheetBuilder.spriteSheet)
        })
        spritesheetBuilder.buildAsync();
        function renderCompleteHandler(sheet) {
            //spritesheet = sheet;
            f(sheet)
            //sprite.play()
        }
    }
}()


///////////========================================================================================================

//export default { Vector } 
window.Vector = /** @class */ (function () {
    //构造函数
    function Vector() {
        var arg = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            arg[_i] = arguments[_i];
        }
        if (arg.length == 1) {
            this.x = arg[0].x;
            this.y = arg[0].y;
        }
        else if (arg.length == 2) {
            if (typeof (arg[0]) == "number") {
                // alert()
                this.x = arg[0];
                this.y = arg[1];
            }
            else {
                this.x = arg[1].x - arg[0].x;
                this.y = arg[1].y - arg[0].y;
            }
        }
        else {
            throw console.error("参数不正确1个或者2个");
        }
        this.angle = Math.atan2(this.y, this.x) * 180 / Math.PI;
        this.length = Math.sqrt(this.x * this.x + this.y * this.y);
    }
    //角度的设置和获取
    Vector.getangle = function (v1, v2) {
        var x = v2.x - v1.x;
        var y = v2.y - v1.y;
        var _angle = Math.atan2(y, x) * 180 / Math.PI;
        return _angle;
    };
    //向量设置角度
    Vector.prototype.setangle = function (a) {
        this.x = this.length * Math.cos(a * Math.PI / 180);
        this.y = this.length * Math.sin(a * Math.PI / 180);
        this.angle = a;
    };
    //大小的设置和获取
    Vector.prototype.getlength = function (v1, v2) {
        var x = v2.x - v1.x;
        var y = v2.y - v1.y;
        //  let _angle = Math.atan2(y, x) * 180 / Math.PI;
        var _length = Math.sqrt(x * x + y * y);
        return _length;
    };
    Vector.prototype.setlength = function (l) {
        var ratio = l / this.length;
        this.length = l;
        this.scale(ratio);
    };
    Vector.prototype.scale = function (s) {
        this.x *= s;
        this.y *= s;
    };
    //以字符串的形式返回向量类的2个属性
    // public toString(): String {
    //     var tx: String = this.x.toFixed(2);
    //     var ty: String = this.y.toFixed(2);
    //     return "[" + tx + "," + ty + "]";
    // }
    Vector.prototype.toString = function () {
        var tx = this.x.toFixed(2);
        var ty = this.y.toFixed(2);
        var tangle = this.angle.toFixed(2);
        var tlength = this.length.toFixed(2);
        return "[x=" + tx + ",y=" + ty + ",angle=" + tangle + ",length=" + tlength + "]";
    };
    Vector.toString2 = function (v) {
        var tx = v.x.toFixed(2);
        var ty = v.y.toFixed(2);
        var angle = Math.atan2(v.y, v.x) * 180 / Math.PI;
        var length = Math.sqrt(v.x * v.x + v.y * v.y);
        var tangle = angle.toFixed(2);
        var tlength = length.toFixed(2);
        return "[x=" + tx + ",y=" + ty + ",angle=" + tangle + ",length=" + tlength + "]";
    };
    //把向量的xy属性赋值给对象
    Vector.prototype.display = function (obj) {
        obj.x = this.x;
        obj.y = this.y;
    };
    //重新初始化
    Vector.prototype.reset = function (x, y) {
        this.x = x;
        this.y = y;
    };
    //得到一个复制的向量
    Vector.prototype.clone = function () {
        return new Vector(this.x, this.y);
    };
    //两个向量相加
    Vector.prototype.plus = function (v) {
        this.x += v.x;
        this.y += v.y;
    };
    //两个向量相加的结果返回给另一个新的向量
    Vector.prototype.plusNew = function (v) {
        return new Vector(this.x + v.x, this.y + v.y);
    };
    //两个向量相减
    Vector.prototype.minus = function (v) {
        this.x -= v.x;
        this.y -= v.y;
    };
    Vector.prototype.minusNew = function (v) {
        return new Vector(this.x - v.x, this.y - v.y);
    };
    //比较两个对象是否相等
    Vector.prototype.equals = function (v) {
        return (this.x == v.x && this.y == v.y);
    };
    //标准化向量
    Vector.prototype.normal = function () {
        var len = this.length;
        return new Vector(this.x / len, this.y / len);
    };
    //判定向量是否为单位向量
    Vector.prototype.isNormalized = function () {
        return length == 1.0;
    };
    //点积
    Vector.prototype.dot = function (v) {
        return this.x * v.x + this.y * v.y;
    };
    //叉乘(即向量的矢量积)
    Vector.prototype.crossProd = function (v) {
        return this.x * v.y - this.y * v.x;
    };
    //当前向量在向量v上的水平投影
    Vector.prototype.parVector = function (v) {
        var len = v.length;
        return v.scaleNew((this.x * v.x + this.y * v.y) / (len * len));
    };
    //当前向量在向量v上的垂直投影
    Vector.prototype.perVector = function (v) {
        return this.minusNew(this.parVector(v));
    };
    //2向量的距离
    Vector.prototype.distance = function (v) {
        var tx = v.x - this.x;
        var ty = v.y - this.y;
        return Math.sqrt(tx * tx + ty * ty);
    };
    //2向量的距离
    Vector.distance = function (v1, v2) {
        var tx = v2?.x - v1?.x;
        var ty = v2?.y - v1?.y;
        return Math.sqrt(tx * tx + ty * ty);
    };
    //----------------------------------------
    //向量求逆，即旋转180度
    Vector.prototype.negate = function () {
        this.x = -this.x;
        this.y = -this.y;
    };
    Vector.prototype.negateNew = function () {
        return new Vector(-this.x, -this.y);
    };
    //向量缩放
    // public scale(s): void {
    //     this.x *= s;
    //     this.y *= s;
    // }
    Vector.prototype.scaleNew = function (s) {
        return new Vector(this.x * s, this.y * s);
    };
    //法向量，返回与当前向量垂直的向量
    Vector.prototype.getNormal = function () {
        return new Vector(-this.y, this.x);
    };
    Vector.prototype.isPerpTo = function (v) {
        return this.dot(v) == 0;
    };
    //向量的夹角
    Vector.prototype.angleBetween = function (v) {
        var dp = this.dot(v);
        var cosAngle = dp / (this.length * v.length);
        var radian = Math.acos(cosAngle);
        return radian * 180 / Math.PI;
    };
    //返回二个向量之间的夹角
    Vector.angleBetween = function (v1, v2) {
        if (!v1.isNormalized()) {
            v1 = v1.clone().normal();
        }
        if (!v2.isNormalized()) {
            v2 = v2.clone().normal();
        }
        return Math.acos(v1.dot(v2)); //建议先回顾一下http://www.cnblogs.com/yjmyzz/archive/2010/06/06/1752674.html中提到的到夹角公式
    };
    //判定给定的向量是否在本向量的左侧或右侧，左侧返回-1，右侧返回1
    Vector.prototype.sign = function (v2) {
        return this.perp().dot(v2) < 0 ? -1 : 1;
    };
    //返回与本向量垂直的向量(即自身顺时针旋转90度，得到一个新向量)
    Vector.prototype.perp = function () {
        return new Vector(-this.y, this.x); //建议回顾一下"坐标旋转"
    };
    return Vector;
}());
//console.log(Vector)

//图形工具
window.Graph = function () {
    //圆上的随机点
    window.circlePot = function (radius, v) {
        let angle = Math.random() * Math.PI * 2;
        let x = Math.cos(angle) * radius + v.x;
        let y = Math.sin(angle) * radius + v.y;
        return new Vector(x, y)
    }
    //圆上每隔多少度出现一个点
    window.circleAngelPots = function (cont, v) {
        let a = 360 / cont
        let angle = 0
        let Ags = []
        // console.log(angle)
        // alert(666)
        for (let i = 0; i < cont; i++) {
            //  
            let x = Math.cos(angle) + v.x;
            let y = Math.sin(angle) + v.y;
            angle += a
            Ags.push(new Vector(x, y))
            // console.log(x)
        }
        // let angle = Math.random() * Math.PI * 2;
        return Ags
    }
}()

